import React, { PropTypes, PureComponent } from 'react';
import { connect, routerRedux } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { FirstHeaderC, TableC, DATA_ENTRY, AdvancedSearch, codeType } from '../../../comps';
import moment from 'moment';
import config from '../../../comps/business/tradingMarket/config';
import { fixedNum } from '../../../utils/utils';

@Form.create()
class BondAbnormal extends PureComponent {
  state = {
    dataSource: [],
    columns: [],
    pageInfo: {},
    startDate: moment(),
    endDate: moment(),
    defStartDate: moment(),
    defEndDate: moment(),
    sortItem: undefined, // 排序字段
    sortType: undefined, // 排序类型
    tradingCode: undefined,
    exchangeCode: undefined,
    isReset: false,
  };

  UNSAFE_componentWillReceiveProps() {
    if (sessionStorage.getItem('workPlaceAbnormal')) {
      let dateObj = JSON.parse(sessionStorage.getItem('workPlaceAbnormal'));
      //默认工作台入参
      this.setState(
        {
          defStartDate: moment(dateObj.startTime).format('YYYYMMDD'),
          defEndDate: moment(dateObj.endTime).format('YYYYMMDD'),
        },
        () => {
          this.getTableData();
          sessionStorage.removeItem('workPlaceAbnormal'); //清空
        },
      );
    }
  }

  //查询条件模块
  searchPart = () => {
    const { defStartDate, defEndDate } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['startDate', 'endDate'],
          title: '日期',
          rules: [{ required: true, message: '请选择起始日期!' }],
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [moment(defStartDate), moment(defEndDate)],
        },
        {
          dataIndex: 'tradingCode',
          title: '证券代码',
          type: DATA_ENTRY.SECURITIESCODE,
          codeType: codeType.zq,
        },
      ],
      onQuery: (e) => {
        this.setState(
          {
            startDate: e ? moment(e.startDate).format('YYYYMMDD') : moment(defStartDate).format('YYYYMMDD'),
            endDate: e ? moment(e.endDate).format('YYYYMMDD') : moment(defEndDate).format('YYYYMMDD'),
            tradingCode: e.tradingCode,
            exchangeCode: e.exchangeCode,
          },
          () => {
            this.getTableData();
          },
        );
      },
      onClear: () => {
        //点击重置按钮
        const { form } = this.props;
        form.resetFields();
        this.setState({
          startDate: '',
          endDate: '',
          sortItem: undefined, // 排序字段
          sortType: undefined, // 排序类型
          isReset: true,
        });
      },
    };
    return (
      <div style={{ marginBottom: '10px' }}>
        {' '}
        <AdvancedSearch {...searchProps} />
      </div>
    );
  };

  //跳转债券详情页面
  onPageJump = (data) => {
    const obj = {
      bondID: data.bondID,
      exchangeCode: data.exchangeCode,
      tradingCode: data.tradingCode,
    };
    sessionStorage.setItem('bondInfo', JSON.stringify(obj));
    this.props.dispatch(routerRedux.push(`/marketAnalysis/bondDeviationDetail`));
  };

  //表格页码排序改变调用
  handleTableChange = (pagination, filt, sorter) => {
    const { current, pageSize } = pagination;
    const { isReset, startDate, endDate } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    if (sorter) {
      if (sorter.order == 'descend') {
        // 降序
        this.setState(
          {
            sortItem: sorter.columnKey, // 排序字段
            sortType: 'descend', // 排序类型
          },
          () => {
            this.getTableData(current, pageSize);
          },
        );
      } else if (sorter.order == 'ascend') {
        // 升序
        this.setState(
          {
            sortItem: sorter.columnKey, // 排序字段
            sortType: 'ascend', // 排序类型
          },
          () => {
            this.getTableData(current, pageSize);
          },
        );
      } else {
        // 无序
        this.setState(
          {
            sortItem: undefined, // 排序字段
            sortType: undefined, // 排序类型
          },
          () => {
            this.getTableData(current, pageSize);
          },
        );
      }
    }
  };

  //获取列表数据
  getTableData = (page, pageSize) => {
    const { dispatch } = this.props;
    const { sortItem, sortType, startDate, endDate, exchangeCode, tradingCode } = this.state;
    //获取个券组列表
    dispatch({
      type: 'BondAbnormalM/getTableData',
      payload: {
        tradingCode: tradingCode,
        exchangeCode: exchangeCode,
        startDate: startDate,
        endDate: endDate,
        sortItem: sortItem,
        sortType: sortType,
        currentPage: page ? page : 1,
        numInPage: pageSize ? pageSize : 20,
      },
      callback: (res) => {
        this.setState({
          dataSource: res.dataSource,
          columns: res.columns,
          pageInfo: res.pageInfo,
        });
      },
    });
  };

  //到期表格靠右
  setColumns = (columns) => {
    const arr = columns;
    if (arr && arr.length) {
      arr.map((item) => {
        //成交日期
        // if (item.key == 'dataDt') {
        //   item.sorter = true;
        //   item.sortOrder = this.state.sortItem == 'dataDt' && this.state.sortType;
        // }
        if (item.key == 'tradingName') {
          item.render = (text, record) => {
            return <a onClick={() => this.onPageJump(record)}>{record.tradingCode + '-' + text}</a>;
          };
        }
        if (item.key == 'exchangeCode') {
          item.render = (text, record) => {
            let findvalue = config.filter((item) => {
              return item.value == text;
            });
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            } else {
              return '--';
            }
          };
        }
        //成交价格||价格偏离度
        if (item.key == 'tradingPriceInterval' || item.key == 'degreePriceInterval') {
          (item.align = 'right'),
            (item.render = (text, record) => {
              if (text) {
                let val = text.split('~');
                return fixedNum(val[0]) + '~' + fixedNum(val[1]);
              }
            });
          // if (item.key == 'degreePriceInterval') {
          //   item.sorter = true;
          //   item.sortOrder = this.state.sortItem == 'degreePriceInterval' && this.state.sortType;
          // }
        }
        //成交收益率||收益率偏离度
        if (item.key == 'tradingRateInterval' || item.key == 'degreeRateInterval') {
          (item.align = 'right'),
            (item.render = (text, record) => {
              if ('113' === record.exchangeCode) {
                if (text) {
                  let val = text.split('~');
                  return fixedNum(val[0]) + '~' + fixedNum(val[1]);
                }
              } else {
                return '--';
              }
            });
          // if (item.key == 'degreeRateInterval') {
          //   item.sorter = true;
          //   item.sortOrder = this.state.sortItem == 'degreeRateInterval' && this.state.sortType;
          // }
        }
        if (item.key == 'statPrice' || item.key == 'statRate' || item.key == 'parvalvol' || item.key == 'principalval') {
          (item.align = 'right'),
            (item.render = (text, record) => {
              return fixedNum(text);
            });
        }
      });
    }
    return arr;
  };

  render() {
    const { columns, dataSource, pageInfo } = this.state;
    const { loading } = this.props;
    const newColumns = this.setColumns(columns);
    return (
      <div>
        <FirstHeaderC title='债券价格异常提醒' />
        {this.searchPart()}
        <div>
          <TableC
            columns={newColumns}
            dataSource={dataSource}
            loading={loading.effects['BondAbnormalM/getTableData']}
            current={pageInfo?.currentPage}
            total={pageInfo?.total}
            pageSize={pageInfo?.numInPage}
            selfScrollY={true}
            // onChange={this.handleTableChange}
            onShowSizeChange={(current, size) => this.getTableData(current, size)}
            onPageChange={(page, pageSize) => this.getTableData(page, pageSize)}
          />
        </div>
      </div>
    );
  }
}
export default connect(({ BondAbnormalM, loading }) => ({ BondAbnormalM, loading: loading }))(BondAbnormal);
